package pubmodel

import (
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ PubRegionModel = (*customPubRegionModel)(nil)

type (
	// PubRegionModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPubRegionModel.
	PubRegionModel interface {
		pubRegionModel
		withSession(session sqlx.Session) PubRegionModel
		Count(ctx context.Context) (int64, error)
		FindAll(ctx context.Context, Current int64, PageSize int64) (*[]PubRegion, error)
	}

	customPubRegionModel struct {
		*defaultPubRegionModel
	}
)

// NewPubRegionModel returns a model for the database table.
func NewPubRegionModel(conn sqlx.SqlConn) PubRegionModel {
	return &customPubRegionModel{
		defaultPubRegionModel: newPubRegionModel(conn),
	}
}

func (m *customPubRegionModel) withSession(session sqlx.Session) PubRegionModel {
	return NewPubRegionModel(sqlx.NewSqlConnFromSession(session))
}

func (m *customPubRegionModel) FindAll(ctx context.Context, Current int64, PageSize int64) (*[]PubRegion, error) {

	query := fmt.Sprintf("select %s from %s limit ?,?", pubRegionRows, m.table)
	var resp []PubRegion
	err := m.conn.QueryRows(&resp, query, (Current-1)*PageSize, PageSize)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *customPubRegionModel) Count(ctx context.Context) (int64, error) {
	query := fmt.Sprintf("select count(*) as count from %s", m.table)

	var count int64
	err := m.conn.QueryRow(&count, query)

	switch err {
	case nil:
		return count, nil
	case sqlc.ErrNotFound:
		return 0, ErrNotFound
	default:
		return 0, err
	}
}
